"""！usr/bin/env python
-*- coding:utf-8 -*-
@FileName: xinghuo_tools.py 
@Author: weiyewang
@Wechat:bluesky___9999
@DateTime: 2025/9/5 11:02
"""
import requests, os, time, base64, html, re
from loguru import logger


class XinghuoTools:
    def __init__(self):
        self.sess = requests.session()

    def xinghuoai_imghandle(self, img_path, prompt, xinghuocookies, xinghuofd, xinghuochatId):
        """
        讯飞星火图片理解能力
        :param img_path: 图片路径
        :param prompt: 提示词
        :param xinghuocookies: cookies
        :param xinghuofd: 请求参数1
        :param xinghuochatId: 请求参数2
        :return: 返回根据给出的提示词对图片理解后的文本信息
        """""
        self.commonheaders = {
            "Host": "xinghuo.xfyun.cn",
            "Origin": "https://xinghuo.xfyun.cn",
            "Referer": "https://xinghuo.xfyun.cn/desk",
            "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Mobile Safari/537.36"
        }
        filepath, ext = os.path.splitext(img_path)
        self.upfiletoken_url = "https://xinghuo.xfyun.cn/iflygpt/oss/sign"
        timestr = int(time.time() * 1000)
        self.upfiletoken_headers = {"Cookie": xinghuocookies}
        self.upfiletoken_headers.update(self.commonheaders)
        data = {"fileName": f"{timestr}{ext}"}
        uptokenres = self.sess.post(self.upfiletoken_url, headers=self.upfiletoken_headers, data=data)
        jsondata = uptokenres.json()["data"]
        authorization, date, host = jsondata["authorization"], jsondata["date"], jsondata["host"]

        self.upfile_url = jsondata["url"]
        self.upfile_headers = {
            "Authorization": authorization,
            "Host": "sgw-dx.xf-yun.com",
            "Origin": "https://xinghuo.xfyun.cn",
            "Referer": "https://xinghuo.xfyun.cn/chat?id=968795437&pre=desk"
        }
        b64auth = base64.b64encode(authorization.encode('utf-8')).decode('utf-8')
        self.upfile_params = {"authorization": b64auth, "date": date, "host": host}
        self.upfile_data = b""
        with open(img_path, 'rb') as f:
            while True:
                data = f.read(65536)
                if not data:
                    break
                self.upfile_data += data
        upfileres = self.sess.post(self.upfile_url, headers=self.upfile_headers, params=self.upfile_params, data=self.upfile_data)
        fileUrl = upfileres.json()["data"]["link"]

        starttime = time.time()
        self.url = "https://xinghuo.xfyun.cn/iflygpt-chat/u/chat_message/chat"
        postheaders = {"Cookie": xinghuocookies}
        postheaders.update(self.commonheaders)
        data = {
            "fd": xinghuofd,
            "clientType": "2",
            "capabilities": ["deep_think", "ifly_search"],  # 深度思考和联网搜索，较耗时
            # "capabilities": ["ifly_search"],  # 仅联网搜索
            "sid": "",
            "chatId": xinghuochatId,
            "text": prompt,
            "fileUrl": fileUrl,
            "GtToken": "RzAwAGMdY130peOLsyD4JUY+yNuRzQzAweNkPWjeu9XpBBSO0cWrqiaQMcAsc2Qb1Syvl2y9MqrZThGrOdsfkA74qJpSGWaPQ3D3sLI90WvKn6zc2Q3kGWONyMidfvTyRgXQzSbKaGWVBSmIZo4kwMPdrF/byPUvDCjpwnAJ1awb0JPnbDLodO1RLU6vaw8MgiyomgA7J1HhNpvjoNWCqySqbDFR61W+zmr4ab2RfPSoYH9NzZUTsqTS4p9VrhitvWwd31yl3ARRayKTilULT72uMDD9wlnM4pcNhSpzT/unRlkSJAF1nq2jgr/FM7aErlBq8LdlDe6jMxbfFnBW6XMha3hhHTdyNLSG7AWdWthaYlKrRDF0OR1JqeKk3nN4CCmAY193h65udP1uNMyqP/L+kUZRHsHQorlVIOcJwj/GJ++c+TfQHuLWne0GZwaijkOTc+mmK8Vo8mr9XLLA4VqDd3sfDJ1pGNR3RfPaNBVLEY+b5DuOdOi/Bc+T4KCMWaQ8z5JjPIFDygLjNY9YrKjtg05rgVHOS5hNxuGCg++ocS9uYVekvW8rrGdRLeA8NaygjzlWzU94od0XMI961QkjIkFN4+DEBA7GRZU6iH7WMmYde+eK5IZ6kYGDvfYpSJyZ4mh0Td3pkf3E12dtHPcyy0oIRZaVfspQiRq5F6sk5FBnwOUWZZGWx8hSld3aR3gYI0K6C8niez9tXh9NnR1if0gv17ZG+p6jnVGRdXfxLucGyRjY0xDVV7MxXZUdUxHsljLzyv9J+SznKzMrfrhOD05sXN1dKQy1199gtPw8QhO+MA/zBH2eEBmdpEK7ElQzp3u8tUZ/y6+ME2lu2CIifTnglS2OvksYb6/6Ucn5PYW5ateZaQe8HCdxkpWy9xJM8+2K9FZPGz5HC1+RbPrExb7e79zZs9oXodbBmBeNC+kyi+BQD/ObbmY7Ph2DcqCBuhhr4e7Yn32iSmuhzTgEQ6uMfO6Ijzq346NnGF2cE820z3iSczmIS+3R167JxlFPwn5iipF4Fl6xCHVqQhLPCbYE8B3QnLTtBuByfERxYoIv6g==",
        }
        res = self.sess.post(self.url, headers=postheaders, data=data, timeout=30)
        datalist = re.findall(r'data:(.*?)\s+', res.text)[:-2]
        clearstr = ""
        for b64bytes in datalist:
            clearstr += base64.b64decode(b64bytes).decode('utf-8')
        clearstr = html.unescape(clearstr)
        try:
            final_text = re.search(r'.*}(.*)', clearstr).group(1)
        except:
            final_text = clearstr
        logger.success(f"星火ai图片处理耗时：{time.time() - starttime:.2f}s， 对话结果：{final_text}")
        return final_text
